import ccxt
import pandas as pd
import datetime
import time
import matplotlib.pyplot as plt

def fetch_ohlcv(exchange, symbol, timeframe, since, limit):
    return exchange.fetch_ohlcv(symbol, timeframe=timeframe, since=since, limit=limit)

def to_timestamp(date_str):
    dt = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
    return int(time.mktime(dt.timetuple()) * 1000)

def main():
    # 初始化交易所实例
    binance = ccxt.binance()
    bitget = ccxt.bitget()

    # 设置交易对、时间框架和历史数据起始时间
    symbol = 'DOGE/USDT'
    timeframe = '5m'
    since = to_timestamp('2024-08-10 00:00:00')  # 起始时间

    # 获取 Binance 和 Bitget 的历史数据
    binance_ohlcv = fetch_ohlcv(binance, symbol, timeframe, since, limit=1000)
    bitget_ohlcv = fetch_ohlcv(bitget, symbol, timeframe, since, limit=1000)

    # 转换为 DataFrame 以便分析
    binance_df = pd.DataFrame(binance_ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
    bitget_df = pd.DataFrame(bitget_ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])

    # 转换时间戳为日期时间格式
    binance_df['timestamp'] = pd.to_datetime(binance_df['timestamp'], unit='ms')
    bitget_df['timestamp'] = pd.to_datetime(bitget_df['timestamp'], unit='ms')

    # 合并两个交易所的数据，按时间戳对齐
    merged_df = pd.merge(binance_df[['timestamp', 'close']], bitget_df[['timestamp', 'close']],
                         on='timestamp', suffixes=('_binance', '_bitget'))

    # 计算价格差异
    merged_df['price_diff'] = merged_df['close_binance'] - merged_df['close_bitget']

    merged_df.to_csv("binance_bitget.csv")

    print(merged_df.head())  # 输出前几行数据
    print("平均价格差异:", merged_df['price_diff'].mean())

    fig, ax1 = plt.subplots(figsize=(14, 7))

    # 画 Binance 价格的折线图，带有条件颜色
    for i in range(len(merged_df) - 1):
        timestamp = merged_df['timestamp'].iloc[i]
        next_timestamp = merged_df['timestamp'].iloc[i + 1]
        binance_price = merged_df['close_binance'].iloc[i]
        next_binance_price = merged_df['close_binance'].iloc[i + 1]

        if merged_df['price_diff'].iloc[i] > 0:
            ax1.plot([timestamp, next_timestamp], [binance_price, next_binance_price], color='green')
        else:
            ax1.plot([timestamp, next_timestamp], [binance_price, next_binance_price], color='red')

    ax1.set_xlabel('Timestamp')
    ax1.set_ylabel('Binance Price (USDT)')
    ax1.set_title('DOGE/USDT Price on Binance (Green: Binance > Bitget, Red: Binance < Bitget)')

    # 创建第二个 y 轴，画二者的价格差异
    ax2 = ax1.twinx()
    ax2.plot(merged_df['timestamp'], merged_df['price_diff'], color='blue', alpha=0.5, label='Price Difference')
    ax2.set_ylabel('Price Difference (USDT)')
    ax2.legend(loc='upper left')

    # 显示网格
    ax1.grid(True)

    # 保存图像
    plt.savefig('doge_usdt_binance_vs_bitget_with_difference.png')

    plt.show()

# 执行主函数
if __name__ == "__main__":
    main()
